from selenium.webdriver.remote.webdriver import WebDriver
from .Selector import Selector
from selenium.webdriver.remote.webelement import *
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class SeleniumPageElement:
    def __init__(self, driver: WebDriver, selector_str, selector_type=Selector):
        self._driver = driver
        self._selector_str = selector_str
        self._selector_type = selector_type

    def wait_element_ready(self, timeout=10, poll_frequency=0.5, recheck=True):
        WebDriverWait(self._driver, timeout, poll_frequency).until(
            EC.presence_of_element_located((Selector.MAP[self._selector_type], self._selector_str)))

    def get_elements(self, wait_flag: bool = True):
        if wait_flag:
            self.wait_element_ready()
        if self._selector_type == Selector.ID:
            elements = self._driver.find_elements_by_id(self._selector_str)
            return elements
        elif self._selector_type == "name":
            elements = self._driver.find_elements_by_name(self._selector_str)
            return elements
        elif self._selector_type == Selector.XPATH:
            elements = self._driver.find_elements_by_xpath(self._selector_str)
            return elements
        elif self._selector_type == Selector.CLASS_NAME:
            elements = self._driver.find_elements_by_class_name(self._selector_str)
            return elements
        elif self._selector_type == Selector.CSS_SELECTOR:
            elements = self._driver.find_elements_by_css_selector(self._selector_str)
            return elements
        elif self._selector_type == "link_text":
            elements = self._driver.find_elements_by_link_text(self._selector_str)
            return elements
        else:
            print("无对应方法，请检查")
            return None

    def click(self, element: WebElement):
        self.wait_element_ready()
        ActionChains(self._driver).move_to_element(element).click(element).perform()

    @staticmethod
    def get_parent_element(element: WebElement) -> WebElement:
        return element.find_element(By.XPATH, "./..")
